package com.gobang.modules.message;

import com.gobang.proto.GameProto.*;
import com.gobang.modules.player.PlayerService;
import com.google.protobuf.ByteString;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息发送服务
 */
@Slf4j
@Service
public class MessageService {

    @Autowired
    private PlayerService playerService;

    /**
     * 发送消息到指定Channel
     */
    public void sendMessage(ChannelHandlerContext ctx, MessageType type, byte[] data) {
        if (ctx == null || !ctx.channel().isActive()) {
            log.warn("Channel不可用，无法发送消息: type={}", type);
            return;
        }

        GameMessage message = GameMessage.newBuilder()
                .setType(type)
                .setData(ByteString.copyFrom(data))
                .build();

        ByteBuf buf = Unpooled.copiedBuffer(message.toByteArray());
        ctx.writeAndFlush(new BinaryWebSocketFrame(buf));
    }

    /**
     * 发送消息到指定玩家
     */
    public void sendToPlayer(Long userId, MessageType type, byte[] data) {
        ChannelHandlerContext ctx = playerService.getChannel(userId);
        if (ctx != null && ctx.channel().isActive()) {
            sendMessage(ctx, type, data);
        } else {
            log.warn("玩家不在线，无法发送消息: userId={}, type={}", userId, type);
        }
    }

    /**
     * 发送错误消息
     */
    public void sendError(ChannelHandlerContext ctx, int code, String msg) {
        ErrorMessage error = ErrorMessage.newBuilder()
                .setCode(code)
                .setMessage(msg)
                .build();
        sendMessage(ctx, MessageType.ERROR, error.toByteArray());
    }

}
